import {reqSendCode,reqRegister,reqLogin,reqUserInfo,reqLoginOut} from "@/api"
import {setToken,getToken,clearToken} from "@/utils/token.js"
const actions = {
      //获取注册验证码
    async getSendCode({commit},{phone}){
       const result=await reqSendCode(phone)
       if(result.code == 200) {
        commit("GETSENDCODE",result.data)
        return "ok"
       }else {
        return Promise.reject(new Error("fail"))
       }
    },


    //获取注册用户
    async getRegister({commit},data) {
      const result = await reqRegister(data)
      if(result.code == 200){
        return "ok"
      }else {
        return Promise.reject(result.message)
      }
    },

    //获取登录
     async getLogin({commit},data){
      const result = await reqLogin(data)
      if(result.code == 200){
        commit('GETLOGIN',result.data.token)
        setToken(result.data.token)
        return "ok"
      }else {
        return Promise.reject(result.message)
      }
    },

     //获取用户信息
   async getUserInfo({commit}){
    const result = await reqUserInfo()
    if(result.code==200){
      commit('GETUSERINFO',result.data)
      return "ok"
    }else {
      return Promise.reject(result.data)
    }
   },

    //退出登录
     async getLoginOut({commit}){
     const result =  await reqLoginOut()
      if(result.code == 200) {
        commit("GETLOGINOUT")
        return "ok"
      }else {
        return Promise.reject(result.message)
      }
    }
}
const mutations = {
  GETSENDCODE(state,sendCode){
      state.sendCode = sendCode
  },

  GETLOGIN(state,token){
    state.token = token
  },

  GETUSERINFO(state,userInfo){
    state.userInfo = userInfo
  },

  GETLOGINOUT(state){
    state.userInfo = ""
    state.token = ""
    clearToken()
  }
}
const state = {
  sendCode:"",
  token:getToken(),
  userInfo:{}
}
const getters = {}

export default {
  namespaced:true,
  actions,
  mutations,
  state,
  getters
}